﻿using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data.Repository.Enum;
using Common.Service;
using Customer360AutoJob.Core.Configuration;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Customer360AutoJob.Jobs
{
    public class ReturnResultChangeDaoRequest : JobBase, IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            List<ChangeDaoRequestRecord> listRequestNeedSendMail = RetrieveListChangeDaoRequest();
            if (listRequestNeedSendMail.Count > 0)
            {
                string mailSubject = "Khoi tao DAO thanh cong";
                listRequestNeedSendMail.ForEach(x =>
                {
                    List<string> listCC = new List<string>();
                    if (!string.IsNullOrEmpty(x.Pic))
                    {
                        listCC.Add(x.Pic + "@vpbank.com.vn");
                    }
                    if (x.ListDaoEmail.Count > 0)
                    {
                        listCC.AddRange(x.ListDaoEmail);
                    }
                    EmailContent content = new EmailContent
                    {
                        Subject = mailSubject,
                        Body = string.Format("Dear anh/chị.{0}Yêu cầu CHD{1} đã được xử lý. Anh/chị vui lòng kiểm tra lại trên T24 và báo lại phòng QTDL nếu có trường hợp nào xử lý sai hoặc thiếu. Khi đó, phòng QTDL sẽ liên hệ với IT để kiểm tra lại. {2}Trân trọng cảm ơn!", Environment.NewLine, x.Id.ToString(), Environment.NewLine),
                        CC = listCC,
                        To = string.Format("{0}@vpbank.com.vn", x.Pic)
                    };
                    if (SendEmail(content))
                    {
                        x.Status = (int)StatusChangeDaoEnum.SendEmail;
                    }
                });
                var listNeedUpdateStatus = listRequestNeedSendMail.Where(x => x.Status == (int)StatusChangeDaoEnum.SendEmail).ToList();
                UpdateStatusChangeDaoAfterSendEmail(listNeedUpdateStatus);
            }
            List<ChangeDaoRequestRecord> listRequestRejectedNeedSendMail = RetrieveListChangeDaoRequestRejected();
            if (listRequestRejectedNeedSendMail.Count > 0)
            {
                string mailSubject = "Khoi tao DAO bi tu choi";
                listRequestRejectedNeedSendMail.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.RejectReason))
                    {

                        List<string> listCC = new List<string>();
                        if (!string.IsNullOrEmpty(x.Pic))
                        {
                            listCC.Add(x.Pic + "@vpbank.com.vn");
                        }
                        //if (x.ListDaoEmail.Count > 0)
                        //{
                        //    listCC.AddRange(x.ListDaoEmail);
                        //}
                        EmailContent content = new EmailContent
                        {
                            Subject = mailSubject,
                            Body = string.Format("Kính gửi anh/ chị {0}, {1} Hiện tại yêu cầu CHD{2} của anh/ chị bị từ chối do {3}.Kính đề nghị anh/ chị thực hiện khởi tạo lại yêu cầu. {4}Trân trọng", x.Pic, Environment.NewLine, x.Id.ToString(), x.RejectReason, Environment.NewLine),
                            CC = listCC,
                            To = string.Format("{0}@vpbank.com.vn", x.Pic)
                        };
                        if (SendEmail(content))
                        {
                            x.Status = (int)StatusChangeDaoEnum.SendRejectEmail;
                        }
                    }
                });
                var listNeedUpdateStatus = listRequestRejectedNeedSendMail.Where(x => x.Status == (int)StatusChangeDaoEnum.SendRejectEmail).ToList();
                UpdateStatusChangeDaoAfterSendEmail(listNeedUpdateStatus);
            }
        }

        private void UpdateStatusChangeDaoAfterSendEmail(List<ChangeDaoRequestRecord> listNeedUpdateStatus)
        {
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UserRecord CurrentUserRecord = new UserRecord
                {
                    UserName = "cucnt3",
                    GroupIdentifier = "1"
                };
                UpdateChangeDaoRequestRequest requestUpdate = new UpdateChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    CurrentUser = CurrentUserRecord,
                    ListChangeDaoRequest = listNeedUpdateStatus
                };
                var result = serviceClient.Proxy.UpdateStatusListChangeDaoRequest(requestUpdate);
            }
        }

        private List<ChangeDaoRequestRecord> RetrieveListChangeDaoRequest()
        {
            RetrieveListChangeDaoRequestResponse result = new RetrieveListChangeDaoRequestResponse();

            FilterRecord filter = new FilterRecord
            {
                CreateDaoRequestStatus = (int)StatusChangeDaoEnum.Done
            };

            UserRecord CurrentUserRecord = new UserRecord
            {
                UserName = "cucnt3",
                GroupIdentifier = "1"
            };
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListChangeDaoRequestRequest request = new RetrieveListChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = 20,
                        PageIndex = 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                result = serviceClient.Proxy.RetrieveListChangeDaoRequestForSendMail(request);
            }
            var listRecord = (result == null || result.Records == null) ? new List<ChangeDaoRequestRecord>() : result.Records;
            return listRecord;
        }
        private List<ChangeDaoRequestRecord> RetrieveListChangeDaoRequestRejected()
        {
            RetrieveListChangeDaoRequestResponse result = new RetrieveListChangeDaoRequestResponse();

            FilterRecord filter = new FilterRecord
            {
                CreateDaoRequestStatus = (int)StatusChangeDaoEnum.Reject
            };

            UserRecord CurrentUserRecord = new UserRecord
            {
                UserName = "cucnt3",
                GroupIdentifier = "1"
            };
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {

                RetrieveListChangeDaoRequestRequest request = new RetrieveListChangeDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManagerController.RetrieveListCreateDaoRequest"
                    },
                    Page = new PageRecord
                    {
                        PageSize = 20,
                        PageIndex = 0
                    },
                    CurrentUser = CurrentUserRecord,
                    Filter = filter
                };
                result = serviceClient.Proxy.RetrieveListChangeDaoRequestForSendMail(request);
            }
            var listRecord = (result == null || result.Records == null) ? new List<ChangeDaoRequestRecord>() : result.Records;
            return listRecord;
        }
    }
}